package util.apps;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.*;

import util.gen.*;

/**Prints out select columns from a tab delimited file, skips lines, appends words, etc. */
public class ABIPeakAreaEstimator {

	//fields
	private File abiTraceFile = null;
	private Pattern tab = Pattern.compile("\\t");
	private ConsensusBase[] consensusBases;
	private int[] seqIndex2PeakIndex;
	private int startIndexMinusOne;
	private int endIndex;
	private int smoothingWindowSize = 26;
	private double minimumFractionTForSmoothing = 0.9;
	
	public ABIPeakAreaEstimator (String[] args) {
		//process args
		processArgs(args);
		
		//load peak indexes
		//loadSeq2PeakIndexes();
		
		//load consensus bases
		loadConsensusBases();
		
		//smooth T's where the T is > 90% any other int
		double[] ts = fetchTs();
	}
	
	public double[] fetchTs(){
		double[] t = new double[consensusBases.length];
		for (int i=0; i< consensusBases.length; i++){
			t[i] = consensusBases[i].fetchT();
		}
	}
	
	/**Loads the look up for the actual consensus call*/
	public void loadSeq2PeakIndexes(){
		try {
			BufferedReader in = new BufferedReader(new FileReader(abiTraceFile));
			String line = null;
			String[] tokens = null;
			//advance to first data line
			boolean foundStart = false;
			while ((line = in.readLine() ) != null){
				if (line.trim().startsWith("Seq")){
					foundStart = true;
					in.readLine();
					break;
				}
			}
			if (foundStart == false) Misc.printErrAndExit("\nError: Could not find the start of your data?\n");
			//for each data line
			ArrayList<Integer> peakIndexes = new ArrayList<Integer>();
			peakIndexes.add(new Integer(0));
			while ((line = in.readLine() ) != null){
				tokens = tab.split(line);
				if (tokens[9].equals("")) break;
				else {
					peakIndexes.add(Integer.parseInt(tokens[9]));
				}
			}
			//convert to array
			seqIndex2PeakIndex = Num.arrayListOfIntegerToInts(peakIndexes);
			in.close();
		} catch (Exception e){
			e.printStackTrace();
		}
	}
		
	public void loadConsensusBases(){
		try {
			BufferedReader in = new BufferedReader(new FileReader(abiTraceFile));
			String line = null;
			String[] tokens = null;
			//advance to first data line
			boolean foundStart = false;
			while ((line = in.readLine() ) != null){
				if (line.trim().startsWith("Seq")){
					foundStart = true;
					in.readLine();
					break;
				}
			}
			if (foundStart == false) Misc.printErrAndExit("\nError: Could not find the start of your data?\n");
			ArrayList<ConsensusBase> cb = new ArrayList<ConsensusBase>();
			//for each data line
			while ((line = in.readLine() ) != null){
				tokens = tab.split(line);
				//is it empty
				if (tokens[0].equals("")) break;
				//is it a consensus
				if (tokens[1].equals(".") == false){
					char consensusBase = tokens[1].charAt(0);
					int g = Integer.parseInt(tokens[2]);
					int a = Integer.parseInt(tokens[3]);
					int t = Integer.parseInt(tokens[4]);
					int c = Integer.parseInt(tokens[5]);
					ConsensusBase x = new ConsensusBase(g,a,t,c,consensusBase);
					//System.out.println(x);
					cb.add(x);
				}
			}
			consensusBases = new ConsensusBase[cb.size()];
			cb.toArray(consensusBases);
			in.close();
		} catch (Exception e){
			e.printStackTrace();
		}
	}
	
	private class ConsensusBase{
		double g;
		double a;
		double t;
		double c;
		char consensusBase;
		double smoothedT;
		double smoothedC;
		
		private ConsensusBase(int g, int a, int t, int c, char consensusBase){
			this.g = g;
			this.a = a;
			this.t = t;
			this.c = c;
			this.consensusBase = consensusBase;
		}
		
		public String toString(){
			return g+"\t"+a+"\t"+t+"\t"+c+"\t"+consensusBase;
		}
		
		public double fetchT(){
			if (consensusBase != 'T') return 0;
			else {
				if ((t/c) < minimumFractionTForSmoothing) return 0;
				if ((t/a) < minimumFractionTForSmoothing) return 0;
				if ((t/g) < minimumFractionTForSmoothing) return 0;
				return t;
			}
		}
	}
	
	
	/**This method will process each argument and assign any new varibles*/
	public void processArgs(String[] args){
		Pattern pat = Pattern.compile("-[a-z]");
		for (int i = 0; i<args.length; i++){
			String lcArg = args[i].toLowerCase();
			Matcher mat = pat.matcher(lcArg);
			if (mat.matches()){
				char test = args[i].charAt(1);
				try{
					switch (test){
					case 'f': abiTraceFile = new File (args[++i]);  break;
					case 'h': printDocs(); System.exit(0);
					case 's': startIndexMinusOne = Integer.parseInt(args[++i]) -1; break;
					case 'e': endIndex = Integer.parseInt(args[++i]); break;
					default: Misc.printExit("\nProblem, unknown option! " + mat.group());
					}
				}
				catch (Exception e){
					Misc.printExit("\nSorry, something doesn't look right with this parameter request: -"+test);
				}
			}
		}
		
	}

	public static void printDocs(){
		System.out.println("\n" +
				"**************************************************************************************\n" +
				"**                           Print Select Columns: July 2006                        **\n" +
				"**************************************************************************************\n" +
				"Spread sheet manipulation.\n\n"+
				
				"Required Parameters:\n"+
				"-f Full path file or directory name for tab delimited text file(s)\n" +
				"-i Column indexs to print, comma delimited, no spaces\n"+
				"-n Number of initial lines to skip\n"+
				"-l Print only this last number of lines\n"+
				"-c Column word to append onto the start of each line\n"+
				"-r Append a row number column as the first column in the output file\n"+
				"-d Append file name onto the start of each line\n"+
				"-s Skip blank lines and those with less than the indicated number of columns.\n"+
	
				"\n" +
				"Example: java -jar pathTo/T2/PrintSelectColumns -f /TabFiles/ -i 0,3,9 -n 1 -c chr\n" +
				"\n" +
		"**************************************************************************************\n");
	}	
	public static void main(String[] args) {
		if (args.length == 0){
			printDocs();
			System.exit(0);
		}
		new ABIPeakAreaEstimator(args);
	}
	
}


